<template>
  <div class="repair-form-container">
    <el-page-header content="宿舍报修" style="margin-bottom: 20px;" />
    
    <el-form
      ref="formRef"
      :model="formData"
      :rules="validationRules"
      label-width="100px"
      class="repair-form"
    >
      <!-- 报修地点 -->
      <el-form-item label="报修地点" prop="location">
        <el-input 
          v-model="formData.location" 
          placeholder="例如：3栋201室" 
        />
      </el-form-item>
      
      <!-- 报修原因 -->
      <el-form-item label="报修原因" prop="reason">
        <el-input 
          type="textarea"
          v-model="formData.reason"
          :rows="4"
          placeholder="请简要描述需要报修的问题"
        />
      </el-form-item>
      
      <!-- 操作按钮 -->
      <el-form-item>
        <el-button 
          type="primary" 
          @click="submitForm" 
          :loading="submitting"
        >
          {{ submitting ? '提交中...' : '提交报修' }}
        </el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';

import {repairForm} from '../../api/student';
import { useUserStore } from '@/store/user'; 

// 获取路由实例
const router = useRouter();

// 表单数据（包含自动填充的studentId）
const formData = reactive({
  studentId: '', // 从本地存储获取
  location: '',
  reason: ''
});

// 表单引用
const formRef = ref(null);

// 提交状态
const submitting = ref(false);

// 表单验证规则
const validationRules = {
  location: [{ required: true, message: '请填写报修地点', trigger: 'blur' }],
  reason: [
    { required: true, message: '请填写报修原因', trigger: 'blur' },
    { min: 5, message: '至少输入5个字符', trigger: 'blur' }
  ]
};

// 生命周期钩子：组件挂载时获取用户信息
onMounted(() => {
    const userStore = useUserStore();
  // 初始化时检查用户是否已登录
  if (!userStore.isLoggedIn) {
    ElMessage.error('请先登录');
    router.push('/login');
    return;
  }
  
  // 从Pinia获取用户信息
  formData.studentId = userStore.userInfo.studentId;
  console.log(formData.studentId)
});

// 提交表单
const submitForm = async () => {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      submitting.value = true;
      
      try {
        // 构造完整的报修数据（包含studentId和时间）
        const repairData = {
          studentId: formData.studentId,
          location: formData.location,
          content: formData.reason,
          repairStatus: '待处理', // 默认状态
          createTime: new Date().toISOString() // 自动生成时间
        
        };

        console.log(formData.studentId)

        // 调用后台API（需根据实际接口调整URL）
        const response = await repairForm(repairData);

        if (response.code === 0) {
          ElMessage.success('报修提交成功！');
          // router.push('/student/repair-list'); // 跳转报修列表
          resetForm(); // 重置表单
        } else {
          ElMessage.error(response.data.message || '提交失败，请重试');
        }
      } catch (error) {
        console.error('API请求失败:', error);
        ElMessage.error('网络错误，请检查网络连接');
      } finally {
        submitting.value = false;
      }
    }
  });
};

// 重置表单
const resetForm = () => {
  formRef.value?.resetFields();
  // 保持studentId不变（用户信息未退出）
  formData.studentId = JSON.parse(localStorage.getItem('userInfo'))?.studentId || '';
};
</script>

<style scoped>
.repair-form-container {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.08);
  max-width: 500px;
  margin: 20px auto;
}

.repair-form {
  width: 100%;
}
</style>